<template>
  <!-- 销售信息录入 -->
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">规格名称:</div>
          <div class="input">
            <el-input v-model="searchList.specificationName" clearable />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="false"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="batch.batchName" label="批次名称" />
        <el-table-column prop="batch.batchNo" label="批次号" />
        <el-table-column prop="customer" label="客户名称" />
        <el-table-column prop="batch.completionDate" label="批次完成时间" />
        <el-table-column prop="batch.lessee" label="种植户" />
        <el-table-column prop="batch.plantingTypeName" label="种养类别" />
        <el-table-column prop="batch.varietyName" label="种养品种" />
        <el-table-column label="售出量">
          <template slot-scope="seedslot">
            {{ seedslot.row.soldValue }}{{ seedslot.row.seedlingUnitName }}
          </template>
        </el-table-column>
        <el-table-column label="售出时间">
          <template v-if="seedslot.row.soldTime" slot-scope="seedslot">
            {{ dateToFormat(seedslot.row.soldTime) }}
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.salesRecordId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="handleEdit(scope.row)"><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '产量规格信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="客户名称:" class="w50p">
            <el-input
              v-model="formData.customer"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="批次选择:" class="w50p">
            <el-select v-model="formData.batchList" clearable :disabled="!canInput" filterable :placeholder="nowbatchName" @change="getspecification">
              <el-option v-for="(item,index) in batchList" :key="item.batchNo" :label="item.batchName" :value="{ value: item.batchNo, plantVarietyId:item.plantVarietyId, farmingTypeNo:item.farmingTypeNo,zhindex:index,plantingTypeName:item.plantingTypeName,lessee:item.lessee,varietyName:item.varietyName}" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="formData.batchList" label="种养品种:" class="w50p">
            <el-input
              v-model="formData.batchList.plantingTypeName"
              :disabled="true"
              clearable
            />
          </el-form-item>
          <el-form-item v-if="formData.batchList" label="种养类别:" class="w50p">
            <el-input
              v-model="formData.batchList.varietyName"
              :disabled="true"
              clearable
            />
          </el-form-item>
          <el-form-item v-if="formData.batchList" label="种植户:" class="w50p">
            <el-input
              v-model="formData.batchList.lessee"
              :disabled="true"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="产量规格" class="w50p">
            <el-select v-model="formData.specificationId" clearable :disabled="!canInput">
              <el-option v-for="(item,index) in specificationList" :key="index" :label="item.specificationName" :value="item.specificationId" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="产出时间:" class="w50p">
            <el-date-picker
              v-model="formData.soldTime"
              type="date"
              :disabled="!canInput"
              format="yyyy-MM-dd"
              clearable
            />
          </el-form-item>
          <el-form-item label="售出数量:" class="w50p">
            <el-input
              v-model="formData.soldValue"
              :disabled="!canInput"
              clearable
            />
            <div v-if="formData.batch">
              {{ formData.batch.unitName }}
            </div>
          </el-form-item>
          <el-form-item label="种苗数量:" class="w50p">
            <el-input
              v-model="formData.seedlingValue"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="售出种苗单位:" class="w50p">
            <el-select v-model="formData.seedlingUnitList" clearable :disabled="!canInput" :placeholder="formData.seedlingUnitName">
              <el-option v-for="(item,index) in unitList" :key="index" :label="item.unitName" :value="{value:item.unitId ,name:item.unitName}" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="产量品级" class="w50p">
            <el-select v-model="formData.grade" clearable :disabled="!canInput">
              <el-option v-for="(item,index) in gradeList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="品种选择" prop="weChat" class="w50p">
            <el-cascader
              v-model="selectplantlist"
              :options="planttypeList"
              :placeholder="nowplantTypeName"
              :disabled="!canInput"
              :props="{ expandTrigger: 'hover',value: 'plantingTypeId',children:'child',label:'plantingTypeName'}"
              @change="getpingzghong"
            />
            <div style="width:20px;"></div>
            <el-select v-model="formData.plantVarietyId" clearable :disabled="!canInput" placeholder="种养品种">
              <el-option v-for="(item,index) in nowvarietyList" :key="index" :label="item.varietyName" :value="item.plantVarietyId" />
            </el-select>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/production-statistics/sales-information-entry";
// import zhongyangleibie from "@/api/basic-info-manage/category-management/index";
// import zhongyangpizhong from "@/api/basic-info-manage/breed-varieties-management/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue"
import unitreq from "@/api/basic-info-manage/unit-manage/index"
import batcjreq from "@/api/digital-production/production-batch-manage/production-batch-query"
import { mymixin } from "@/utils/mixin"
import SearchBox from '@/components/SearchBox';
// import { getToken } from '@/utils/auth';
export default {
  name: "SalesInfromationEntry",
  components: { ActionBar, Pagination, BaseMainSlot, SearchBox },
  mixins: [mymixin],
  data() {
    return {
      // 下拉选择框相关
      // 批次选择列表
      batchList: [],
      // 产量规格
      specificationList: [],
      // 产量单位
      unitList: [],
      // 产量品级
      // gradeList: [
      //   { name: "优", id: 1 },
      //   { name: "良", id: 2 },
      //   { name: "差", id: 3 }
      // ],
      // -- 种养类别相关 --后来者直接换下位置即可
      selectplantlist: [],
      nowplantTypeName: "种养类别",
      planttypeList: [],
      nowvarietyList: [],
      // --------
      batchfarmtypeid: "", // 跟着批次走的农业类型id
      // 搜索框对象
      searchList: {
      },
      // 选中的数据项数组
      nowselectedList: [],
      // 当前选中的批次名称
      nowbatchName: "",
      dialogTitle: null,
      dialogFormVisible: false
    };
  },
  watch: {
    nowChanceStau(newvalue) {
      if (newvalue === 'add' || newvalue === '') {
        this.formData = {
          batchList: {}
        }
      }
    }
  },
  created() {
  },
  mounted() {
    this.getTableDataList()
    this.getselectdatalist()
  },
  methods: {
    // 获取下拉框数据
    getselectdatalist() {
      // 获取单位列表
      unitreq.getallunitlist().then(
        res => {
          this.unitList = res.data
        }
      )
      // 批次选择
      batcjreq.querybylist({ status: false }).then(
        res => {
          this.batchList = res.data
        }
      )
    //   // 获取种养类别树状表
    //   zhongyangleibie.getplantingTypeTree().then(
    //     (res) => {
    //       let list = res.data
    //       this.planttypeList = this.filterTreeKey(list)
    //     }
    //   )
    },
    // 通过品种id查产量规格
    getspecification(e) {
      let id = e.plantVarietyId
      // console.log(e)
      this.batchfarmtypeid = e.farmingTypeNo
      nowpagereq.getspecification(id).then(
        res => {
          this.specificationList = res.data
        }
      )
    },
    // 通过种养类别id查品种
    // getpingzghong(e) {
    //   let params = {
    //     plantingTypeId: this.selectplantlist[this.selectplantlist.length - 1]
    //   }
    //   zhongyangpizhong.querybycondition(params).then(
    //     res => {
    //       this.nowvarietyList = res.data
    //     }
    //   )
    // },
    // 通过种养品种id查品种name
    // getvarriety(id) {
    //   let params = {
    //     plantVarietyId: id
    //   }
    //   zhongyangpizhong.querybycondition(params).then(
    //     res => {
    //       this.nowvarietyList = res.data
    //     }
    //   )
    // },
    // 获取当前拥有类型表格
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize
      }
      nowpagereq.getlist(params).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error('表格获取失败')
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
        this.formData = {
          batchList: {
          }
        }
      });
    },
    search() {
      this.currentPage = 1;
      // 暂时直接当作表格查询
      this.getTableDataList();
    },
    add() {
      this.openDialog('add');
      this.formData = {};
    },
    handleEdit(row) {
      // console.log(row)
      // if (row.indflag) {
      //   this.$message.warning("请勿选择空数据")
      //   return
      // }
      // this.getvarriety(row.plantVarietyId)
      // this.getpingzghongname(row.plantingTypeId)
      this.formData = row;
      this.nowbatchName = row.batch.batchName
      this.formData.batchList = { value: row.batch.batchNo,
        plantVarietyId: row.batch.plantVarietyId,
        farmingTypeNo: row.batch.farmingTypeNo,
        lessee: row.batch.lessee,
        varietyName: row.batch.varietyName,
        plantingTypeName: row.batch.plantingTypeName,
        unitId: row.batch.unit
      }
      this.openDialog('edit');
    },
    cancel() {
      this.closeDialog();
      this.formData = {};
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.salesRecordId
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      if (this.nowChanceStau === 'del') {
        nowpagereq.dellist(this.nowselectedList).then(
          res => {
            if (res.code === 1) {
              this.getTableDataList()
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          }
        )
        this.nowChanceStau = ''
      }
    },
    handleDelete(data) {
      nowpagereq.dellist([data.salesRecordId]).then(
        res => {
          if (res.code === 1) {
            this.getTableDataList()
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败')
          }
        }
      )
    },
    save() {
      if (this.nowChanceStau === 'add') {
        let nowbatchmessage = this.batchList[ this.formData.batchList.zhindex]
        let addparams = {
          ...this.formData,
          organizationNo: nowbatchmessage.organizationNo,
          batchNo: this.formData.batchList.value,
          plantVarietyId: nowbatchmessage.plantVarietyId,
          plantingTypeId: nowbatchmessage.plantingTypeId,
          plantingTypeName: nowbatchmessage.plantingTypeName,
          varietyName: nowbatchmessage.varietyName,
          soldUnitId: nowbatchmessage.unitId,
          seedlingUnitId: this.formData.seedlingUnitList.value,
          seedlingUnitName: this.formData.seedlingUnitList.name,
          farmingTypeNo: this.batchfarmtypeid // 这是跟着批次农业类型id
        }
        delete addparams.seedlingUnitList
        addparams.soldTime = this.dateToFormattwo(addparams.soldTime)
        delete addparams.batchList
        console.log(addparams)
        nowpagereq.addlist(addparams).then(
          res => {
            if (res.code === 1) {
              this.getTableDataList()
              this.closeDialog();
              this.$message.success('添加成功')
            } else {
              this.$message.error('添加失败')
            }
          }
        )
      }
      if (this.nowChanceStau === 'edit') {
        let editparams = {
          ...this.formData
        }
        if (editparams.soldUnitId) {
          delete editparams.soldUnitId
        }
        if (this.formData.batchList) {
          let nowbatchmessage = this.batchList[ this.formData.batchList.zhindex]
          editparams.organizationNo = nowbatchmessage.organizationNo
          editparams.plantVarietyId = nowbatchmessage.plantVarietyId
          editparams.plantingTypeId = nowbatchmessage.plantingTypeId
          editparams.plantingTypeName = nowbatchmessage.plantingTypeName
          editparams.varietyName = nowbatchmessage.varietyName
          editparams.soldUnitId = nowbatchmessage.unitId
          editparams.batchNo = this.formData.batchList.value
          delete editparams.batchList
        }
        if (this.formData.seedlingUnitList) {
          editparams.seedlingUnitId = this.formData.seedlingUnitList.value
          editparams.seedlingUnitName = this.formData.seedlingUnitList.name
        }
        editparams.soldTime = this.dateToFormattwo(editparams.soldTime)
        console.log(editparams)
        nowpagereq.editlist(editparams).then(
          res => {
            if (res.code === 1) {
              this.getTableDataList()
              this.closeDialog();
              this.$message.success('修改成功')
            } else {
              this.$message.error('修改失败')
            }
          }
        )
      }
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === 'add' ? '新增' : '编辑'
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = '';
    }
  }
};
</script>
<style lang="scss" scoped>
</style>
